package com.spzx.order.receiver;

import com.rabbitmq.client.Channel;
import com.spzx.common.rabbit.constant.MqConst;

import com.spzx.order.configure.DelayedMqOrderConfig;
import com.spzx.order.domain.OrderInfo;
import com.spzx.order.service.IOrderInfoService;

import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;

@Component
public class OrderReceiver {

    @Autowired
    IOrderInfoService orderInfoService;

    @RabbitListener(queues = DelayedMqOrderConfig.QUEUE_ORDER_CANCEL_DELAY)
    public void a(Channel channel, Message message, String orderNo) throws IOException {
        // 幂等性校验
        // TODO
        OrderInfo orderInfoByOrderNo = orderInfoService.getOrderInfoByOrderNo(orderNo);

        System.out.println("20分钟之后用户如果未支付订单，则关闭订单，释放库存");
        orderInfoService.cancelOrder(orderNo);
        channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
    }

    @RabbitListener(bindings = @QueueBinding(
            exchange = @Exchange(durable = "true",value = MqConst.EXCHANGE_PAYMENT_PAY),
            key = {MqConst.ROUTING_PAYMENT_PAY},
            value = @Queue(durable = "true",value = MqConst.QUEUE_PAYMENT_PAY)
    ))
    public void b(Channel channel, Message message, String orderNo) throws IOException {
        // 幂等性校验
        // TODO
        OrderInfo orderInfoByOrderNo = orderInfoService.getOrderInfoByOrderNo(orderNo);

        System.out.println("根据订单号，修改订单状态为已支付:"+orderNo);
        orderInfoService.updateOrderSuccess(orderNo);

        channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);

    }
}
